package com.netted.operationassistant.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.netted.operationassistant.R;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.http.HttpRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArouseActivity extends BaseActivity{

    private String password;
    private String account;
    private String userId;

    private EditText catbinet_code;
    private EditText catbinet_name;
    private EditText catbinet_count;
    private Spinner shengSpinner;
    private Spinner citySpinner;
    private Spinner schoolSpinner;


    private JSONArray areaJsonArr = null;

    private JSONArray cityJsonArr = null;
    private JSONArray schoolJsonArr = null;

    private Button submitBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arouse);
        submitBtn = (Button)findViewById(R.id.arouse_submit_btn);
        catbinet_code = (EditText)findViewById(R.id.catbinet_code);
        catbinet_name = (EditText)findViewById(R.id.catbinet_name);
        catbinet_count = (EditText)findViewById(R.id.catbinet_count);
        catbinet_count.setEnabled(false);
        catbinet_count.setFocusable(false);
        catbinet_count.setKeyListener(null);
        shengSpinner = (Spinner)findViewById(R.id.sheng_spinner);
        citySpinner = (Spinner)findViewById(R.id.city_spinner);
        schoolSpinner = (Spinner) findViewById(R.id.school_spinner);
        catbinet_count.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    submit(null);
                    return true;
                }
                return false;
            }
        });
        Intent intent = getIntent();
        password = intent.getStringExtra("password");
        account = intent.getStringExtra("account");
        userId = intent.getStringExtra("userId");




        catbinet_code.setText(catbinetCode);
        catbinet_name.setText(catbinetName);
        catbinet_count.setText(catbinetPortCount);
        if ("".equals(catbinetId) && "".equals(catbinetId) && "".equals(catbinetId) && "".equals(catbinetId) ){
            if (StringUtils.isEmpty(password) || StringUtils.isEmpty(account) || StringUtils.isEmpty(userId)){
                ActivityUtils.finishToActivity(LoginActivity.class,true);
            }
            showArea();
            getPort();
        }else{
            submitBtn.setText("已激活");
            submitBtn.setEnabled(false);
            submitBtn.setClickable(false);
            if ("".equals(catbinetId) || "".equals(catbinetId) || "".equals(catbinetId) || "".equals(catbinetId) ){
                showDialog("错误提示","该机柜数据丢失,请解除绑定机柜,并重新绑定指定机柜数据",null);
            }else{
                catbinet_code.setEnabled(false);
                catbinet_name.setEnabled(false);
                catbinet_count.setEnabled(false);
                bindArea();
            }
        }
    }


    public void getPort(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                for(int i = 0; i < 3; i ++){
                    getPortCount(  i);
                    try {
                        Thread.sleep(1000);
                        if (!"".equals(serialValue)){
                            boolean b = verify(serialValue);
                            if(b){
                                String[] arr = serialValue.split(" ");
                                sharedPreferencesHelper.put(Constant.XML_BROAD_ + i,Integer.parseInt(arr[arr.length - 3]));
                                count += Integer.parseInt(arr[arr.length - 3]);
                            }else{
//                    showDialog("提示","校验错误",null);
                            }
                        }else{
//                showDialog("提示","无应答,该板不存在!",null);
                        }
                        serialValue = "";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                final int c = count;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        catbinet_count.setText(c+"");
                    }
                });
            }
        }).start();


    }


    public void init(){




    }

    public void bindArea(){
        if("".equals(Constant.AREA_JSON) || null == Constant.AREA_JSON || "".equals(schoolId) || "".equals(schoolName)
                 || "".equals(schoolAreaId)){
            return;
        }
        JSONArray areaJsonArr = JSONArray.parseArray(Constant.AREA_JSON);
        for(int i = 0; i < areaJsonArr.size(); i ++){
            JSONArray cityJsonArr = areaJsonArr.getJSONObject(i).getJSONArray("citys");
            if (cityJsonArr != null && cityJsonArr.size() > 0){
                for(int j = 0; j < cityJsonArr.size(); j ++){
                    String cityId = cityJsonArr.getJSONObject(j).get("id")+"";
                    if (cityId.equals(schoolAreaId)){
                        List<String> cityList = new ArrayList<>();
                        cityList.add(cityJsonArr.getJSONObject(j).getString("name"));
                        ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,cityList);
                        citySpinner.setAdapter(cityAdapter);
                        citySpinner.setEnabled(false);

                        List<String> shengList = new ArrayList<>();
                        shengList.add(areaJsonArr.getJSONObject(i).getString("name"));
                        ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,shengList);
                        shengSpinner.setAdapter(shengAdapter);
                        shengSpinner.setEnabled(false);


                        List<String> schoolList = new ArrayList<>();
                        schoolList.add(schoolName);
                        ArrayAdapter<String> schoolAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,schoolList);
                        schoolSpinner.setAdapter(schoolAdapter);
                        schoolSpinner.setEnabled(false);
                    }
                }
            }

        }
    }

    //显示可选地区和学校
    public void showArea(){
        if("".equals(Constant.AREA_JSON) || null == Constant.AREA_JSON){
            return;
        }
        areaJsonArr = JSONArray.parseArray(Constant.AREA_JSON);
        if (areaJsonArr.size() > 0){
            List<String> sList = new ArrayList<>(areaJsonArr.size());
            for(int i = 0; i < areaJsonArr.size(); i ++){

                sList.add( areaJsonArr.getJSONObject(i).getString("name"));

            }
            ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,sList);
            shengSpinner.setAdapter(shengAdapter);
        }

        shengSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                JSONArray citys = areaJsonArr.getJSONObject(i).getJSONArray("citys");
                bindCitys(citys);
                LogUtils.e(areaJsonArr.getJSONObject(i).getString("id") +
                        "---------------"+areaJsonArr.getJSONObject(i).getString("name"));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    public void submit(View view){

        final ProgressDialog loadingDialog = ProgressDialog.show(this,"Loading...", "读取中...", true, false);
        final String code = catbinet_code.getText().toString();
        final String name = catbinet_name.getText().toString();
        final String count = catbinet_count.getText().toString();
        if ("".equals(code)){
            ToastUtils.showLong("请填写完整识别码");
            loadingDialog.dismiss();
            return;
        }

        if ("".equals(name)){
            ToastUtils.showLong("请填写完整名称");
            loadingDialog.dismiss();
            return;
        }
        if ("".equals(count)){
            ToastUtils.showLong("请填写完整仓口数量");
            loadingDialog.dismiss();
            return;
        }

        if (null == schoolId || "".equals(schoolId)){
            ToastUtils.showLong("请选择学校");
            loadingDialog.dismiss();
            return;
        }
        Map<String,String> params = new HashMap<>();
        params.put("code",code);
        params.put("name",name);
        params.put("count",count);
        params.put("userId",userId);
        params.put("password",password);
        params.put("account",account);
        params.put("schoolId",schoolId);
        request.post(Constant.HOST+"/ws/opt/activateCatbinet",params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try{
                    if (!StringUtils.isEmpty(response)){
                        JSONObject json = JSONObject.parseObject(response);
                        if ("success".equals(json.getString("flag"))){
                            catbinet_code.setEnabled(false);
                            catbinet_name.setEnabled(false);
                            catbinet_count.setEnabled(false);
                            JSONObject catbinetJson = JSONObject.parseObject(json.getString("data"));
                            String id = catbinetJson.getString("id");
                            sharedPreferencesHelper.put(Constant.XML_CATBINET_ID,id);
                            sharedPreferencesHelper.put(Constant.XML_CATBINET_CODE,code);
                            sharedPreferencesHelper.put(Constant.XML_CATBINET_NAME,name);
                            sharedPreferencesHelper.put(Constant.XML_SCHOOL_ID,schoolId);
                            sharedPreferencesHelper.put(Constant.XML_CATBINET_PORT_COUNT,count);
                            sharedPreferencesHelper.put(Constant.XML_SCHOOL_NAME,schoolName);
                            sharedPreferencesHelper.put(Constant.XML_SCHOOL_AREA_ID,schoolAreaId);




                            ToastUtils.showLong("保存成功");
                            ActivityUtils.finishToActivity(MainActivity.class,false);
                            return;
                        }else{
                            ToastUtils.showLong(json.getString("message"));
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                ToastUtils.showLong(response);
            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                LogUtils.e(JSONObject.toJSONString(error));
                ToastUtils.showShort(JSONObject.toJSONString(error));
            }

        });



    }


    private void bindCitys(JSONArray citys){
        cityJsonArr = citys;
        List<String> cityList = new ArrayList<>();
        if (citys != null && citys.size() > 0){
            for(int i = 0; i < citys.size(); i ++){
                cityList.add(citys.getJSONObject(i).getString("name"));
            }
        }
        ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,cityList);
        citySpinner.setAdapter(shengAdapter);
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String cityId = cityJsonArr.getJSONObject(i).getString("id");
                LogUtils.e(cityJsonArr.getJSONObject(i).getString("id")
                        +"------"+schoolId+"---------"+cityJsonArr.getJSONObject(i).getString("name"));

                getSchool(cityId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    public void getSchool(String id){
        final ProgressDialog progressDialog = ProgressDialog.show(this,"Loading...", "正在读取学校列表...", true, false);
        String url = Constant.HOST + "/ws/opt/getSchool";
        Map<String,String> params = new HashMap<>();

        params.put("area",id);

        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                progressDialog.dismiss();
                if (response != null){
                    JSONObject json = JSONObject.parseObject(response);
                    if ("success".equals(json.getString("flag"))){
                        String data = json.getString("data");
                        if (data == null || "".equals(data)){
                            showDialog("提示","该地区无学校记录",null);
                            return;
                        }
                        JSONArray dataJsonArr = JSONArray.parseArray(data);

                        bindSchool(dataJsonArr);
                        return;
                    }
                }
                showDialog("提示","获取学校记录出错",null);
            }

            @Override
            public void onError(VolleyError error) {
                progressDialog.dismiss();
                showDialog("提示","获取学校记录出错",null);
            }
        });
    }


    private void bindSchool(JSONArray dataJsonArr){
        schoolJsonArr = dataJsonArr;
        schoolId = null;
        List<String> sList = new ArrayList<>();
        if (dataJsonArr != null && dataJsonArr.size() > 0){
            for(int i = 0; i < dataJsonArr.size(); i ++){
                sList.add(dataJsonArr.getJSONObject(i).getString("name"));
            }
        }

        ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,sList);
        schoolSpinner.setAdapter(shengAdapter);
        schoolSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                schoolId = schoolJsonArr.getJSONObject(i).getString("id");
                schoolName = schoolJsonArr.getJSONObject(i).getString("name");
                schoolAreaId = schoolJsonArr.getJSONObject(i).getString("area");
                LogUtils.e(schoolJsonArr.getJSONObject(i).getString("id") +
                        "---------------"+schoolJsonArr.getJSONObject(i).getString("name") +
                        "---------------"+schoolJsonArr.getJSONObject(i).getString("area"));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    public void  exitActivity(View view){
        Intent intent = new Intent(this,AdminMenuActivity.class);
        intent.putExtra("account",account);
        intent.putExtra("password",password);
        intent.putExtra("userId",userId);
        startActivity(intent);
        this.finish();
    }



}
